﻿using System.Web;
using System.IO;
using AjaxPro;
using SGRapidForm.Common;
using System.Configuration;
using SGRapidForm.Permission.Entity;
using SGRapidForm.Permission.Service.Interface;

namespace SGRapidForm.Module
{
    public class FilterModule : IHttpModule
    {
        private IPermissionService _permissionService = ServiceProxyFactory.Create<IPermissionService>("permissionservice");

        #region IHttpModule 成员

        public void Init(HttpApplication context)
        {
            //获取会话信息
            context.AcquireRequestState += (o, e) =>
            {
                string ContextKey = "SGRapidForm.Common.ApplicationContext";

                HttpApplication application = (HttpApplication)o;

                #region 不验证的页面

                switch (application.Request.CurrentExecutionFilePath.ToLower())
                {
                    case "/start.aspx":
                    case "/login.aspx":
                    case "/fillquestion.aspx":
                    case "/retrievepassword.aspx":
                    case "/help/help.aspx":
                    case "/help/helplist.aspx":
                    case "/help/helpitem.aspx":
                    case "/views/permission/common/shortcutslist.aspx":
                    case "/error.htnl": 
                    case "/error_404.html": return;
                }

                #endregion

                #region 是否开启权限控制

                // 如果没有开启则跳过控制
                string enabledPermissionsControl = ConfigurationManager.AppSettings["EnabledPermissionsControl"].ToLower();
                if (enabledPermissionsControl.Equals("false"))
                {
                    return;
                }
                #endregion

                #region  请求信息

                //页面编码"UserList"
                string pageCode = Path.GetFileNameWithoutExtension(application.Request.CurrentExecutionFilePath);
                //页面扩展名,例如 “.aspx“
                string currentExecutionFilePathExtension = application.Request.CurrentExecutionFilePathExtension.ToLower();
                //请求类型 ”GET“/”POST“
                string requestType = application.Request.RequestType;
                bool ret = false;

                #endregion 

                #region 是否登录的验证

                switch (application.Request.CurrentExecutionFilePath.ToLower())
                {
                    case "/choosetodept.aspx":
                    case "/main.aspx":
                    case "/oahome.aspx":
                    case "/home.aspx":
                        if (application.Context.Session != null && application.Context.Session.SessionID != null && application.Context.Session[ContextKey] != null)
                        {
                            return;
                        }
                        else
                        {
                            context.Response.Redirect("~/Error_404.html", true);
                        }  
                    ;return;
                }

           

                #endregion

                #region .aspx的验证
                /*
                 *  1,判断是否是ASPX
                 *  2,判断是否登录
                 *  3,判断时候有页面权限
                 *  未登录，无权限则取消当前会话，并且跳转到Error_404.html
                 */
                if (currentExecutionFilePathExtension == ".aspx")
                {
                    if (application.Context.Session != null && application.Context.Session.SessionID != null && application.Context.Session[ContextKey] != null)
                    {
                        ret = _permissionService.User_HasPagePermission(ApplicationContext.Current.UserKeyid, pageCode);
                        //无权限
                        if (!ret)
                        {
                            context.Response.Redirect("~/Error_404.html", true);
                        }
                        return;
                    }
                    else
                    {
                        context.Response.Redirect("~/Error_404.html", true);
                    }
                }

                #endregion

                #region Ajax调用的验证 
                /*
                 *  1,判断是否是Ajax调用
                 *  2,判断是否登录
                 *  3,判断时候有按钮权限
                 *  未登录，无权限则取消当前会话，并且终止响应
                 */

                //if (application.Request.RequestType.Equals("POST") && application.Request.Path.StartsWith("/ajaxpro/"))
                //{
                //    if (application.Context.Session != null && application.Context.Session.SessionID != null && application.Context.Session[ContextKey] != null)
                //    {
                //        ret = _permissionService.User_HasButtonPermission(ApplicationContext.Current.UserKeyid, this.GetPageCode(pageCode), this.GetServerSideMethod(application));
                //        //无权限
                //        if (!ret)
                //        {
                //            application.Response.End();
                //        }
                //    }
                //    else
                //    {
                //        application.Response.End();
                //    }
                //}

                #endregion
            };
        }

        public void Dispose()
        {
        }

        #endregion

        /// <summary>
        /// 获取文件名称
        /// </summary>
        /// <param name="pageCode"></param>
        /// <returns></returns>
        protected string GetPageCode(string pageCode)
        {
            pageCode = pageCode.Substring(0, pageCode.IndexOf(','));
            pageCode = pageCode.Substring(pageCode.LastIndexOf('.') + 1);
            return pageCode;
        }

        /// <summary>
        /// 获取方法名
        /// </summary>
        /// <param name="application"></param>
        /// <returns></returns>
        protected string GetServerSideMethod(HttpApplication application)
        {
            string methodName = application.Request.Headers["X-" + Constant.AjaxID + "-Method"];
            if (methodName == null || methodName.Length == 0)
            {
                methodName = application.Request["X-" + Constant.AjaxID + "-Method"];
            }
            return methodName;
        }
    }
}
